package io.framework.modules.noise.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.framework.common.page.PageData;
import io.framework.common.service.impl.CrudServiceImpl;
import io.framework.modules.noise.dao.NoiseMonitorDao;
import io.framework.modules.noise.dto.NoiseMonitorDTO;
import io.framework.modules.noise.entity.NoiseMonitorEntity;
import io.framework.modules.noise.service.NoiseMonitorService;
import io.framework.modules.station.dto.StationDTO;
import io.framework.modules.station.service.StationService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 噪音 环境质量监测
 *
 * @author Gujq email
 * @since 1.0.0 2020-06-01
 */
@Service
public class NoiseMonitorServiceImpl extends CrudServiceImpl<NoiseMonitorDao, NoiseMonitorEntity, NoiseMonitorDTO> implements NoiseMonitorService {

    @Autowired
    private StationService stationService;

    @Override
    public QueryWrapper<NoiseMonitorEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<NoiseMonitorEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public Boolean checkData(String year, Integer type) {
        Boolean flag = false;
        List<NoiseMonitorEntity> list = baseDao.checkData(year,type);
        if (CollectionUtils.isNotEmpty(list)) {
            flag = true;
        }
        return flag;
    }

    @Override
    public int deleteInfoByDate(Map<String, Object> params) {

        return baseDao.deleteInfoByDate(params);
    }

    @Override
    public List<Map<String, Object>> statistics(Map<String, Object> params) {

        Integer classify = Integer.parseInt(params.get("classify").toString());
        List<Map<String, Object>> resultMapList = new ArrayList<>();
        String stationId[] = params.get("stationId").toString().replaceAll(" ", "").split(",");
        for (String id : stationId) {
            Long sid = Long.parseLong(id);
            params.put("stationId", sid);
            StationDTO stationDTO = stationService.get(sid);
            if (stationDTO != null) {
                Map<String, Object> resultMap = new HashMap<>();
                List<Map<String, Object>> mapArrayList = new ArrayList<>();
                List<Map<String, Object>> mapList = baseDao.statistics(params);
                mapList.forEach(L -> {
                    L.forEach((k, v) -> {
                        Map<String, Object> map = new HashMap<>();
                        switch (k) {
                            case "Leq":
                                map.put("name", "Leq");
                                map.put("value", v);
                                mapArrayList.add(map);
                                break;
                            case "L10":
                                map.put("name", "L10");
                                map.put("value", v);
                                mapArrayList.add(map);
                                break;
                            case "L50":
                                map.put("name", "L50");
                                map.put("value", v);
                                mapArrayList.add(map);
                                break;
                            case "L90":
                                map.put("name", "L90");
                                map.put("value", v);
                                mapArrayList.add(map);
                                break;
                            case "Lmax":
                                map.put("name", "Lmax");
                                map.put("value", v);
                                mapArrayList.add(map);
                                break;
                            case "Lmin":
                                map.put("name", "Lmin");
                                map.put("value", v);
                                mapArrayList.add(map);
                                break;
                            case "SD":
                                map.put("name", "标准差（SD）");
                                map.put("value", v);
                                mapArrayList.add(map);
                                break;
                            case "large":
                                map.put("name", "大型汽车（辆/20min）");
                                map.put("value", v);
                                if (classify == 1) {
                                    mapArrayList.add(map);
                                }
                                break;
                            case "small":
                                map.put("name", "中小型汽车（辆/20min）");
                                map.put("value", v);
                                if (classify == 1) {
                                    mapArrayList.add(map);
                                }
                                break;
                        }
                    });
                });

                resultMap.put("stationName", stationDTO.getName());
                resultMap.put("listData", mapArrayList);
                resultMapList.add(resultMap);
            }
        }
        return resultMapList;
    }

    @Override
    public Map<String, Object> statistics_new(Map<String, Object> params) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
        if (!params.containsKey("time")) {
            params.put("time", LocalDate.now().format(formatter));
        }
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(params));
        if (jsonObject.getInteger("time") < 1990) {
            return null;
        }
        Integer classify = jsonObject.getInteger("classify");
        if (classify.equals(1)) {//1-交通噪声 2-区域噪声
            params.put("type", 1);
            params.put("query", ">70");
            List<Map<String, Object>> jtzcCount = baseDao.statistics_new(params);
            params.put("query", "<=70");
            List<Map<String, Object>> jtzdCount = baseDao.statistics_new(params);
            params.put("type", 2);
            params.put("query", ">55");
            List<Map<String, Object>> jtycCount = baseDao.statistics_new(params);
            params.put("query", "<=55");
            List<Map<String, Object>> jtydCount = baseDao.statistics_new(params);
            map.put("jtzcCount", jtzcCount);//交通白超标
            map.put("jtzdCount", jtzdCount);//交通白达标
            map.put("jtycCount", jtycCount);//交通夜超标
            map.put("jtydCount", jtydCount);//交通夜达标
            if ((jtzcCount.isEmpty() || jtzcCount.size() == 0) && (jtzdCount.isEmpty() || jtzdCount.size() == 0)
                    && (jtycCount.isEmpty() || jtycCount.size() == 0) && (jtydCount.isEmpty() || jtydCount.size() == 0)) {
                params.put("time", LocalDate.of(jsonObject.getInteger("time"), 1, 1).minusYears(1).format(formatter));
                return statistics_new(params);
            }
        } else {
            params.put("zoneCode", 1);
            params.put("type", 1);
            params.put("query", ">55");
            List<Map<String, Object>> qyz1cCount = baseDao.statistics_new(params);
            params.put("query", "<=55");
            List<Map<String, Object>> qyz1dCount = baseDao.statistics_new(params);
            params.put("type", 2);
            params.put("query", ">45");
            List<Map<String, Object>> qyy1cCount = baseDao.statistics_new(params);
            params.put("query", "<=45");
            List<Map<String, Object>> qyy1dCount = baseDao.statistics_new(params);
            params.put("zoneCode", 2);
            params.put("type", 1);
            params.put("query", ">60");
            List<Map<String, Object>> qyz2cCount = baseDao.statistics_new(params);
            params.put("query", "<=60");
            List<Map<String, Object>> qyz2dCount = baseDao.statistics_new(params);
            params.put("type", 2);
            params.put("query", ">50");
            List<Map<String, Object>> qyy2cCount = baseDao.statistics_new(params);
            params.put("query", "<=50");
            List<Map<String, Object>> qyy2dCount = baseDao.statistics_new(params);
            if ((qyz1cCount.isEmpty() || qyz1cCount.size() == 0) && (qyz1dCount.isEmpty() || qyz1dCount.size() == 0)
                    && (qyy1cCount.isEmpty() || qyy1cCount.size() == 0) && (qyy1dCount.isEmpty() || qyy1dCount.size() == 0)
                    && (qyz2cCount.isEmpty() || qyz2cCount.size() == 0) && (qyz2dCount.isEmpty() || qyz2dCount.size() == 0)
                    && (qyy2cCount.isEmpty() || qyy2cCount.size() == 0) && (qyy2dCount.isEmpty() || qyy2dCount.size() == 0)) {
                params.put("time", LocalDate.of(jsonObject.getInteger("time"), 1, 1).minusYears(1).format(formatter));
                return statistics_new(params);
            }
            map.put("qyz1cCount", qyz1cCount);//区域1类白超标
            map.put("qyz1dCount", qyz1dCount);//区域1类白达标
            map.put("qyy1cCount", qyy1cCount);//区域1类夜超标
            map.put("qyy1dCount", qyy1dCount);//区域1类夜达标
            map.put("qyz2cCount", qyz2cCount);//区域2类白超标
            map.put("qyz2dCount", qyz2dCount);//区域2类白达标
            map.put("qyy2cCount", qyy2cCount);//区域2类夜超标
            map.put("qyy2dCount", qyy2dCount);//区域2类夜达标
        }
        map.put("time", jsonObject.getString("time"));
        return map;
    }

    @Override
    public Map<String, Object> getNoiseInfo(Map<String, Object> params) {

        Map<String, Object> m = baseDao.getNoiseInfo(params);

        return m;
    }

    @Override
    public PageData<NoiseMonitorDTO> pageList(Map<String, Object> params) {
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(params));
        String orderField = jsonObject.getString("orderField");
        String order = jsonObject.getString("order");
        String time = jsonObject.getString("time");
        Integer page = jsonObject.getInteger("page");
        Integer limit = jsonObject.getInteger("limit");
        Integer classify = jsonObject.getInteger("classify");
        QueryWrapper<NoiseMonitorEntity> queryWrapper = new QueryWrapper<>();
        if (classify != null) {
            queryWrapper.eq("classify", classify);
        }
        if (StringUtils.isNotBlank(time)) {
            queryWrapper.eq("date_format(month,'%Y')", time);
        }
        Page<NoiseMonitorEntity> p = new Page<>(page, limit);
        if (StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)) {
            if (order.equals("desc")) {
                queryWrapper.orderByDesc(orderField);
            } else {
                queryWrapper.orderByAsc(orderField);
            }
        }
        IPage<NoiseMonitorEntity> ip = baseDao.selectPage(p, queryWrapper);
        List<NoiseMonitorDTO> dtoList = JSONArray.parseArray(JSONArray.toJSONString(ip.getRecords()), NoiseMonitorDTO.class);
        for (NoiseMonitorDTO noiseMonitorDTO : dtoList) {
            //1-交通噪声 2-区域噪声
            if (noiseMonitorDTO.getClassify().equals(1)) {
                //1-昼间 2-夜间
                if (noiseMonitorDTO.getType().equals(1)) {
                    setDtoPass(noiseMonitorDTO, new BigDecimal(70));
                } else if (noiseMonitorDTO.getType().equals(2)) {
                    setDtoPass(noiseMonitorDTO, new BigDecimal(55));
                }
            } else if (noiseMonitorDTO.getClassify().equals(2)) {
                //1-昼间 2-夜间
                if (noiseMonitorDTO.getType().equals(1)) {
                    //功能区代码 1-1类，2-2类
                    if (noiseMonitorDTO.getZoneCode().equals("1")) {
                        setDtoPass(noiseMonitorDTO, new BigDecimal(55));
                    } else if (noiseMonitorDTO.getZoneCode().equals("2")) {
                        setDtoPass(noiseMonitorDTO, new BigDecimal(60));
                    }
                } else if (noiseMonitorDTO.getType().equals(2)) {
                    //功能区代码 1-1类，2-2类
                    if (noiseMonitorDTO.getZoneCode().equals("1")) {
                        setDtoPass(noiseMonitorDTO, new BigDecimal(45));
                    } else if (noiseMonitorDTO.getZoneCode().equals("2")) {
                        setDtoPass(noiseMonitorDTO, new BigDecimal(50));
                    }
                }
            }
        }
        return new PageData<NoiseMonitorDTO>(dtoList, ip.getTotal());
    }

    private void setDtoPass(NoiseMonitorDTO noiseMonitorDTO, BigDecimal leq) {
        //1-达标  2-超标
        if (noiseMonitorDTO.getLeq().compareTo(leq) > 0) {
            noiseMonitorDTO.setPass(2);
        } else {
            noiseMonitorDTO.setPass(1);
        }
    }
}
